/**
 * @作者 faner
 * @创建时间 2021/2/23 14:52
 */
package com.faner.fast.activiti;

import com.faner.fast.annotation.AnonymousAccess;
import com.faner.fast.util.R;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@Api(value = "ActiviBusiness", tags = "ActiviBusiness模块")
public class ActiviBusinessController {

    @AnonymousAccess
    @ApiOperation("添加业务key")
    @ApiOperationSupport(order = 10,author = "faner")
    @RequestMapping(value = "/activi/key",method= {RequestMethod.GET})
    public R initSelectParams(){
        //1.创建ProcessEngine
        final ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        final RuntimeService runtimeService = defaultProcessEngine.getRuntimeService();
       //2.启动流程过程中，添加businesskey
//            第一个参数 流程定义的key
//            第二个参数 BusinessKey 存出差申请单id
        final ProcessInstance myEvection = runtimeService.startProcessInstanceByKey("myEvection","1001");
        return  R.ok(myEvection.getBusinessKey());
    }

    @AnonymousAccess
    @ApiOperation("全部业务流程挂起与激活")
    @ApiOperationSupport(order = 10,author = "faner")
    @RequestMapping(value = "/activi/suspend",method= {RequestMethod.GET})
    public R suspend(){
        //表task
        //1.创建ProcessEngine
        final ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        final RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();
        //2.查询流程定义
        final ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("myEvection")
                .singleResult();
        //2.查询流程是否挂起
        final boolean suspended = processDefinition.isSuspended();
        if (suspended){
            //挂起的激活 参数一 流程定义id 参数2 是否激活 参数三 激活时间
           repositoryService.activateProcessDefinitionById(processDefinition.getId(),true,null);
        }else{
            //激活的挂起
            repositoryService.suspendProcessDefinitionById(processDefinition.getId(),true,null);
        }
        return  R.ok();
    }

    @AnonymousAccess
    @ApiOperation("单个业务流程挂起与激活")
    @ApiOperationSupport(order = 10,author = "faner")
    @RequestMapping(value = "/activi/single",method= {RequestMethod.GET})
    public R single(){
        //表task
        //1.创建ProcessEngine
        final ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        final RuntimeService runtimeService = defaultProcessEngine.getRuntimeService();
        //2.查询流程定义
        final ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId("fe3d0a29-75b7-11eb-873c-6807157c728e").singleResult();

        //2.查询流程是否挂起
        final boolean suspended = processInstance.isSuspended();
        if (suspended){
            //挂起的激活 参数一 流程定义id 参数2 是否激活 参数三 激活时间
            runtimeService.activateProcessInstanceById(processInstance.getId());
        }else{
            //激活的挂起
            runtimeService.suspendProcessInstanceById(processInstance.getId());
        }
        return  R.ok();
    }

    @AnonymousAccess
    @ApiOperation("完成个人任务")
    @ApiOperationSupport(order = 10,author = "faner")
    @RequestMapping(value = "/activi1/completask",method= {RequestMethod.GET})
    public R completask(){
        final ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //2.获取TaskService
        final TaskService taskService = defaultProcessEngine.getTaskService();
        //3.根据流程key与负责人查询
        Task task = taskService.createTaskQuery()
                .processInstanceId("fe3d0a29-75b7-11eb-873c-6807157c728e")
                .taskAssignee("zhangsan")
                .singleResult();
        taskService.complete(task.getId());
        return  R.ok();
    }




    @AnonymousAccess
    @ApiOperation("查询组任务")
    @ApiOperationSupport(order = 10,author = "faner")
    @RequestMapping(value = "/activi1/findGroup",method= {RequestMethod.GET})
    public R findGroup(){
        //流程定义key
        String key = "group-1";
        //任务候选人
        String candidateUser = "admin";
        final ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //2.获取TaskService
        final TaskService taskService = defaultProcessEngine.getTaskService();
      //3.查询组任务
        final List<Task> list = taskService.createTaskQuery()
                .processDefinitionKey(key)
                .taskCandidateUser(candidateUser)
                .list();
        final List<Object> collect = list.stream().map(t -> {
            Map<Object, Object> map = new HashMap<>();
            map.put("流程实例id", t.getProcessInstanceId());
            map.put("任务id", t.getId());
            map.put("任务负责人id", t.getAssignee());
            map.put("任务名称", t.getName());
            return map;
        }).collect(Collectors.toList());
        return  R.ok(collect);
    }


    @AnonymousAccess
    @ApiOperation("拾取组任务")
    @ApiOperationSupport(order = 10,author = "faner")
    @RequestMapping(value = "/activi1/claimTask",method= {RequestMethod.GET})
    public R claimTask(){
        final ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //2.获取TaskService
        final TaskService taskService = defaultProcessEngine.getTaskService();
        //3.拾取的任务id
        String taskId= "afc11a28-7649-11eb-a44c-6807157c728e";
        //3.拾取的候选人id
        String candidateUser = "admin";
        //拾取任务
        //即便该用户不是候选人也能拾取（建议拾取时校验是否有资格）
        //校验该用户有没有拾取任务的资格
       Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .taskCandidateUser(candidateUser)
                .singleResult();
        if (task!=null){
            //拾取任务
            taskService.claim(taskId,candidateUser);
            System.out.println("拾取成功");
        }
        return  R.ok();
    }


    @AnonymousAccess
    @ApiOperation("归还组任务")
    @ApiOperationSupport(order = 10,author = "faner")
    @RequestMapping(value = "/activi1/assignee",method= {RequestMethod.GET})
    public R assigneeTask(){
        final ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //2.获取TaskService
        final TaskService taskService = defaultProcessEngine.getTaskService();
        //3.拾取的任务id
        String taskId= "afc11a28-7649-11eb-a44c-6807157c728e";
        //3.拾取的负责人id
        String candidateUser = "admin";
        //故意换任务
        //校验该用户有没有拾取任务的资格
        Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .taskAssignee(candidateUser)
                .singleResult();
        if (task!=null){
            //归还任务
            taskService.setAssignee(taskId,null);
            System.out.println("归还任务成功");
        }
        return  R.ok();
    }


    @AnonymousAccess
    @ApiOperation("任务交接")
    @ApiOperationSupport(order = 10,author = "faner")
    @RequestMapping(value = "/activi1/setAssigneeToCandidateUser",method= {RequestMethod.GET})
    public R setAssigneeToCandidateUser(){
        final ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //2.获取TaskService
        final TaskService taskService = defaultProcessEngine.getTaskService();
        //3.任务id
        String taskId= "afc11a28-7649-11eb-a44c-6807157c728e";
        //3.任务负责人id
        String candidateUser = "admin";

        //3.转给其他人
        String tocandidateUser = "222";
        //校验该用户是否时该任务的负责人，如果时负责人才可以归还任务
        Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .taskAssignee(candidateUser)
                .singleResult();
        if (task!=null){
            //任务交接
            taskService.setAssignee(taskId,tocandidateUser);
            System.out.println("任务交接成功");
        }
        return  R.ok();
    }
}
